//
//  LGTUserSetVC.swift
//  KJLGT
//
//  Created by jenkin on 2019/8/16.
//  Copyright © 2019年 jenkin. All rights reserved.
//

import UIKit

class LGTUserSetVC: LGTBaseVC, UITableViewDelegate, UITableViewDataSource{

    var tableView:UITableView?
    var data:Array<Any>?
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func setUI() {
        super.setUI()
        self.setBavBarStyle(navBarHiden: false, title: "设置", back: true)
        self.tableView = UITableView.init(frame: CGRect.init(x: 0.0, y: NavBarH, width: Double(KScreenW), height: Double(KScreenH) - NavBarH), style: UITableView.Style.plain)
        self.view.addSubview(self.tableView!)
        self.tableView?.backgroundColor = ViewBackColor
        self.tableView?.separatorStyle = UITableViewCell.SeparatorStyle.none
        self.tableView?.delegate = self
        self.tableView?.dataSource = self
        self.tableView?.register(LGTUserInfoViewCell.classForCoder(), forCellReuseIdentifier: "cell")
    }
    
    override  func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.setData()
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.data?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
        return self.data?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.data == nil{
            return 0
        }
        
        let data:Array<Any> = self.data?[section] as! Array<Any>
        return data.count
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return SizeFitFloat(10.0)
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView.init()
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return SizeFitFloat(KRate * 44.0)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:LGTUserInfoViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! LGTUserInfoViewCell
        let data:Array<Any> = self.data?[indexPath.section] as! Array<Any>
        let dict:Dictionary<String, Any> = data[indexPath.row] as! Dictionary<String, Any>
        cell.data = dict
        
        let isPush:Bool = (dict["isPush"] ?? false) as! Bool
        let isCache:Bool = (dict["isCache"] ?? false) as! Bool
        if isPush == true{
            let switchView:UISwitch = UISwitch.init(frame: CGRect.init(x: 0.0, y: 0.0, width: SizeFit(60), height: SizeFit(30)))
            switchView.backgroundColor = SwitchBackColor
            switchView.onTintColor = ColorUtil(color: 0x4CDA64)
            switchView.thumbTintColor = UIColor.white
            switchView.layer.masksToBounds = true
            switchView.layer.cornerRadius = CGFloat(SizeFit(15))
            switchView.addTarget(self, action: #selector(switchAction), for: UIControl.Event.valueChanged)
            cell.accessoryView = switchView
        } else if isCache == true{
            let view:UILabel = LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.right, textColor: TextColor, fontSize: UserCell_Set_Size, text: dict["cacheStr"] as! String)
            view.frame =  CGRect.init(x: 0.0, y: 0.0, width: SizeFit(200), height: Double(UserCell_Set_Size))
            cell.accessoryView = view
        }else{
            cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        if section == 2{
          let view:UIView = UIView.init()
          view.backgroundColor = UIColor.clear
          let quitButton = LGTViewCreateUtil.share.createTextLGTButton(title: "退出登录", font: Font_Normal_16, color: UIColor.white, selectedColor: UIColor.white, corner: CGFloat(SizeFit(22)), backColor:ColorUtil(color: 0xC9C9C9))
          quitButton.addTarget(self, action: #selector(quitAction), for: UIControl.Event.touchUpInside)
            quitButton.frame = CGRect.init(x: SizeFit(12), y: SizeFit(80), width: Double(KScreenW) - SizeFit(24), height: SizeFit(44))
          view.addSubview(quitButton)
          return view
        }
        
        return UIView.init()
    }
    
    @objc func switchAction(){
        let urlObj = URL(string:UIApplication.openSettingsURLString)
        if #available(iOS 10.0, *) {
            UIApplication.shared.open(urlObj! as URL, options: [ : ], completionHandler: { Success in
                
            })} else {
            UIApplication.shared.openURL(urlObj!)
        }
        
    }
    
    //退出登录
    @objc func quitAction(){
        let alertVC = UIAlertController.init(title: "确定退出登录", message: "", preferredStyle: UIAlertController.Style.alert)
        weak var weakSelf = self
        let playAction = UIAlertAction.init(title: "确定", style: UIAlertAction.Style.default) { (action) in
            weakSelf?.clearData()
        }
        let cancelAction = UIAlertAction.init(title: "取消", style: UIAlertAction.Style.default) { (action) in
            
        }
        alertVC.addAction(playAction)
        alertVC.addAction(cancelAction)
        self.present(alertVC, animated: true, completion: nil)
    }
    
    func clearData(){
        self.tabBarController?.selectedIndex = 0
        let mainVC:UINavigationController =  self.tabBarController?.viewControllers?[0] as! UINavigationController
        mainVC.pushViewController(LGTMainLoginVC(), animated: true)
        self.navigationController?.popViewController(animated: false)
        //清理数据
        LGTUserUtil.share.clearUserInfo()
        UserModel.share = nil
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == 2{
            let height  = SizeFit(124)
            return CGFloat(height)
        }
        return 1
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: false)
        if indexPath.section == 2{
            self.navigationController?.pushViewController(LGTAboutusVC(), animated: true)
        }else if indexPath.section == 0{
            if indexPath.row == 1{
                if UserModel.share?.is_password == 1{
                    let updateVC:LGTUpdatePaswordVC = LGTUpdatePaswordVC()
                    self.navigationController?.pushViewController(updateVC, animated: true)
                }else{
                    let resetVC:LGTForgetPasswordVC = LGTForgetPasswordVC()
                    resetVC.isForgetVC = false
                    self.navigationController?.pushViewController(resetVC, animated: true)
                }
            }
        }
        
        if indexPath.section == 1{
            //清理缓存
            if indexPath.row == 0{
                self.clearCache()
            }else{
                let vc:LGTAdviceFeedVC = LGTAdviceFeedVC()
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }
    }
    
    //清理缓存
    func clearCache(){
        let alertVC = UIAlertController.init(title: "是否清除缓存", message: "", preferredStyle: UIAlertController.Style.alert)
        weak var weakSelf = self
        let playAction = UIAlertAction.init(title: "确定", style: UIAlertAction.Style.default) { (action) in
            BaseUtil.baseUtil.removeCache()
            weakSelf?.setData()
        }
        let cancelAction = UIAlertAction.init(title: "取消", style: UIAlertAction.Style.default) { (action) in
            
        }
        alertVC.addAction(playAction)
        alertVC.addAction(cancelAction)
        self.present(alertVC, animated: true, completion: nil)
    }
    
    func setData(){
        
        var pass:String = "修改密码"
        if UserModel.share?.is_password == 0{
            pass = "设置密码"
        }
        let cacheStr = BaseUtil.baseUtil.getCacheSize()
        let data:Array = [
            [
                ["title":"推送设置", "push": true, "isPush": true],
                ["title":pass]
            ],
            [
                ["title":"清除缓存", "text":"", "isCache": true, "cacheStr": cacheStr],
                ["title":"意见反馈", "text":""]
            ],
            [
                ["title":"关于我们", "text":""],
                ],] as [Any]
        
        self.data = data
        self.tableView?.reloadData()
    }
}
